package com.example.demoexample.utils;

import android.text.TextUtils;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by songdongliang on 2016/11/16.
 */

public class TimeUtil {

    /**
     * 15:00    分:秒
     *
     * @param time 毫秒
     * @return
     */
    public static String formatMinuteAndSecond(long time) {
        int second = (int) (time / 1000);
        return second / 60 + ":" + (second % 60 < 10 ? ("0" + second % 60) : second % 60);
    }

    /**
     * 10:02    时:分
     *
     * @param time 毫秒
     * @return
     */
    public static String formatHourAndMinute(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute);
    }

    public static String formatHourAndMinute(long time, String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return (hour < 10 ? "0" + hour : hour) + format + (minute < 10 ? "0" + minute : minute);
    }

    public static String formatYearNoHour(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DATE);
        return year + "-" + (month < 10 ? "0" + month : month) + "-" + (day < 10 ? "0" + day : day);
    }

    public static String getFormatStrByDate(String format, Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        return sdf.format(date);
    }

    public static String getFormatStrByDate(String format, long time) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        return sdf.format(date);
    }

    public static String formatMsgTime(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        Calendar currentCalendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int currentDay = currentCalendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        if (Math.abs(currentDay - day) == 1) {
            return "昨天" + (hour < 10 ? ("0" + hour) : hour) + ":" + (minute < 10 ? ("0" + minute) : minute);
        } else if (Math.abs(currentDay - day) > 1) {
            return calendar.get(Calendar.MONTH) + 1 + "月" + (day < 10 ? ("0" + day) : day) + "日";
        } else {
            return (hour < 10 ? ("0" + hour) : hour) + ":" + (minute < 10 ? ("0" + minute) : minute);
        }
    }

    /**
     * 10:02    时:分
     *
     * @param time 毫秒
     * @return
     */

    public static String formatHourAndMinuteC(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return (hour < 10 ? "0" + hour : hour) + "时" + (minute < 10 ? "0" + minute : minute) + "分";
    }

    /**
     * 获取当前年月格式为:yyyy-MM
     *
     * @param date
     * @return
     */
    public static String getMonth(Date date) {
        int month = date.getMonth() + 1;
        return (date.getYear() + 1900) + "-" + (month > 9 ? month : "0" + month);
    }

    /**
     * 获取当前年月的上一个月格式为:yyyy-MM
     *
     * @param date
     * @return
     */
    public static String getPreMonth(Date date) {
        int month = date.getMonth();
        if (month <= 0) {
            return (date.getYear() + 1899) + "-12";
        } else {
            return (date.getYear() + 1900) + "-" + (month > 9 ? month : "0" + month);
        }

    }

    /**
     * 获取当前年月的上两个月格式为:yyyy-MM
     *
     * @param date
     * @return
     */
    public static String getPreSecondMonth(Date date) {
        int month = date.getMonth();
        if (month == 0) {
            return (date.getYear() + 1899) + "-11";
        } else if (month == 1) {
            return (date.getYear() + 1899) + "-12";
        } else {
            return (date.getYear() + 1900) + "-" + ((month - 1) > 9 ? (month - 1) : "0" + (month - 1));
        }
    }

    public static Date getDate(String str) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        try {
            Date date = sdf.parse(str);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Date getDateByFormat(String format, String str) {
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getDifferenceValue(Date date1, Date date2) {
        long duration = getDuration(date1, date2);
        return formatHourAndMinuteC((int) duration / 1000);
    }

    public static long getDuration(Date date1, Date date2) {
        return date2.getTime() - date1.getTime();
    }

    public static String formatHourAndMinuteC(int second) {
        int h = second / (60 * 60);
        int s = (second % (60 * 60)) / 60;
        StringBuffer sb = new StringBuffer();
        if (h > 0) {
            sb.append(h + "时");
        }
        if (s >= 0) {
            sb.append(s + "分");
        }
        return sb.toString();
    }

    public static String formatHourAndMinuteString(long second) {
        long h = second / (60 * 60);
        long s = (second % (60 * 60)) / 60;
        StringBuffer sb = new StringBuffer();
        if (h > 0) {
            sb.append(h + "时");
        }
        if (s >= 0) {
            sb.append(s + "分");
        }
        return sb.toString();
    }

    public static String strToMonthAndDay(String time) {
        if (time == null) return "";
        String[] dates = time.split(" ");
        String[] strs = dates[0].split("-");
        return strs[1] + "月" + strs[2] + "日";
    }

    public static String timeToMonthAndDay(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        StringBuilder sb = new StringBuilder(16);
        int month = calendar.get(Calendar.MONTH) + 1;
        if (month < 10) sb.append("0");
        sb.append(month);
        sb.append("月");
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (day < 10) sb.append("0");
        sb.append(day);
        sb.append("日");
        return sb.toString();
    }

    public static String formatHourAndMinute(String time) {
        if (TextUtils.isEmpty(time)) return "";
        return formatHourAndMinuteC(TimeUtil.getDate(time).getTime());
    }

    public static String getDurationByStr(String from, String to) {
        if (TextUtils.isEmpty(from) || TextUtils.isEmpty(to)) return "";
        return TimeUtil.getDifferenceValue(TimeUtil.getDate(from), TimeUtil.getDate(to));
    }

    public static String formatStandard(long time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        Date date = new Date();
        date.setTime(time);
        return sdf.format(date);
    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 通过时间格式的字符串得到周几
     *
     * @param time
     * @return
     */
    public static String getWeekByStr(String time) {
        if (TextUtils.isEmpty(time)) return "";
        return getWeekOfDate(getDate(time));
    }

    public static String getWeekOfTimeStamp(long time) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);

        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 两个时间的差值是否满足被给的duration
     *
     * @param start    开始时间
     * @param end      结束时间
     * @param duration 单位为小时
     * @return
     */
    public static boolean timeDifferentValue(long start, long end, int duration) {
        return duration >= (end - start) / 1000 / 60 / 60;
    }

    /**
     * 获取该月的天数
     *
     * @param month
     * @return
     */
    public static int getDaysOfMonth(int month) {
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
        }
        return 0;
    }

    /**
     * 计算两个时间相差的天数
     *
     * @param beginDate
     * @param endDate
     * @return
     */
    public static int getTimeDistance(long beginDate, long endDate) {
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTimeInMillis(beginDate);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTimeInMillis(endDate);
        long beginTime = beginCalendar.getTime().getTime();
        long endTime = endCalendar.getTime().getTime();
        int betweenDays = (int) ((endTime - beginTime) / (1000 * 60 * 60 * 24));//先算出两时间的毫秒数之差大于一天的天数

        endCalendar.add(Calendar.DAY_OF_MONTH, -betweenDays);//使endCalendar减去这些天数，将问题转换为两时间的毫秒数之差不足一天的情况
        endCalendar.add(Calendar.DAY_OF_MONTH, -1);//再使endCalendar减去1天
        if (beginCalendar.get(Calendar.DAY_OF_MONTH) == endCalendar.get(Calendar.DAY_OF_MONTH))//比较两日期的DAY_OF_MONTH是否相等
            return betweenDays + 1;    //相等说明确实跨天了
        else
            return betweenDays + 0;    //不相等说明确实未跨天
    }

    // 计算两个时间的差 单位为分钟
    public static long getTimeDifferHour(long time) {
        Calendar calendar = Calendar.getInstance();
        long difMis = calendar.getTimeInMillis() - time;    // 相差的毫秒数
        long hours = difMis / (1000 * 60);
        return hours > 0 ? hours : 0;
    }


    /**
     * 获取几个小时后的时间
     *
     * @param time
     * @param hour
     * @return
     */
    public static long getHourAfter(long time, int hour) {
        long tt = 60 * 60 * 1000 * hour;
        time = time + tt;
        return time;
    }


    /**
     * Date转String
     *
     * @param date
     * @return
     */
    public static String getDateToString(String format, Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String str = sdf.format(date);
        return str;
    }

    public static Date getYearAfter(int time, int year) {
        Calendar ca = Calendar.getInstance();
        ca.setTimeInMillis(time);
//         设置时间为当前时间
        ca.add(Calendar.YEAR, year);
        // 年份减1
        Date lastMonth = ca.getTime(); //结果
        return lastMonth;
    }

    /**
     * 返回指定年月的月的最后一天
     *
     * @return
     */
    public static long getLastDayOfMonth(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        calendar.set(year, month, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTimeInMillis();
    }

    public static long getDayOfMonth(long time, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.add(Calendar.MONTH, month);
        return calendar.getTimeInMillis();
    }

    /**
     * 返回指定日期的上个月的最后一天
     *
     * @return
     */
    public static long getLastDayOfLastMonth(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) - 1, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTimeInMillis();
    }

    /**
     * 返回下个月的最后一天
     *
     * @return
     */
    public static long getLaterDayOfLastMonth(long time) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(time);
        calendar.set(calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1, 1);
        calendar.roll(Calendar.DATE, -1);
        return calendar.getTimeInMillis();
    }

    public static String getHourForSecend(long secend) {
        float hour = secend / 60.0f / 60.0f;
        DecimalFormat df=new DecimalFormat("0.00");//设置保留位数
        return df.format(hour);
    }

}
